package com.itmuch.cloud.study.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.itmuch.cloud.study.entity.MaterialTransport;
import com.itmuch.cloud.study.service.EmailOptionService;
import com.itmuch.cloud.study.service.TransportService;
import com.itmuch.cloud.study.util.EmailUtil;
import com.itmuch.cloud.study.util.ExcelUtils;
import com.itmuch.cloud.study.util.JsGridReportBase;
import com.itmuch.cloud.study.util.TableData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by 齐丹枫 on 2017/3/23 13:11.
 */

@Service
public class EmailOptionServiceImpl implements EmailOptionService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private TransportService transportService;

    public Date date = new Date();
    public SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    ;

    @Override
    public boolean saveEmailSendInfo(String sender, List<String> receiver, String status) {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String receiverStr = "";
        if(receiver != null && receiver.size() != 0){
            receiverStr = String.join(",",receiver);
        }

        StringBuffer stringBuffer = new StringBuffer("insert into t_emailLog " +
                "(id,sender,receiver,sendTime,sta) values" +
                "('" + UUID.randomUUID().toString() + "','" + sender + "','" + receiverStr + "','" + sdf.format(date) + "','" + status + "')");
        int i = jdbcTemplate.update(stringBuffer.toString());

        if (i == 1) {
            return true;
        }







       /* try {
            jdbcTemplate.batchUpdate(stringBuffer.toString(), new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    ps.setString(1, UUID.randomUUID().toString());
                    ps.setString(2, sender);
                    ps.setString(3, receiver);
                    ps.setString(4, portIds.get(i));
                    ps.setString(5, sdf.format(date));
                    ps.setString(6, stas.get(i));
                }

                @Override
                public int getBatchSize() {
                    return portIds.size();
                }
            });
        } catch (DataAccessException e) {
        //    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }*/
        return false;
    }

    public List<MaterialTransport> sendEmailInfo() {

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateStart = sdf.format(date);
        String dateEnd = sdf.format(date);

       /* String dateStart = "2017-03-20 00:00:00";
        String dateEnd = "2017-03-30 23:59:59";*/
        String s = transportService.find(dateStart, dateEnd, "", "", "", "", "");

        JSONObject jb = JSONObject.parseObject(s);

        Object datas = jb.get("datas");

        List<Map<String, String>> lists = (List<Map<String, String>>) datas;

        Set<MaterialTransport> mts = new HashSet<MaterialTransport>();

        List<MaterialTransport> materialTransports = new ArrayList<MaterialTransport>();

        if (lists != null && lists.size() != 0) {
            for (Map<String, String> map : lists
                    ) {
                MaterialTransport mt = new MaterialTransport();
                mt.setPlantCode(map.get("plantCode"));
                mt.setPlantName(map.get("plantName"));
                mt.setDelivery(map.get("delivery"));
                mt.setMaterial(map.get("material"));
                mt.setProductCode(map.get("productCode"));
                mt.setDescription(map.get("description"));
                mt.setDeliveryQty(map.get("deliveryQty"));
                mt.setSendDeliveryQty(String.valueOf(map.get("sendDeliveryQty")));
                mt.setFlag(map.get("flag"));
                mts.add(mt);
            }
        }


        materialTransports.addAll(mts);

        return materialTransports;
    }

    @Override
    public boolean sendEmail(String sender, Map<String, List<String>> receiver, String content, String subject) {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        List<String> re = new ArrayList<String>();
        re.add("QianApple.dai@kcc.com");
        re.add("945621734@qq.com");

        String path = "";
        List<MaterialTransport> mts = sendEmailInfo();   //所有DC的数据

        Map<String, List<MaterialTransport>> maps = new HashMap<String, List<MaterialTransport>>(); //各DC的数据

        /**
         * 从所有数据中分类，把各DC的数据通过Map存放
         */
        if (mts != null && mts.size() != 0) {

            for (MaterialTransport mt : mts) {
                String plantCode = mt.getPlantCode();
                if (maps.containsKey(plantCode)) {
                    maps.get(plantCode).add(mt);
                } else {
                    List<MaterialTransport> lists = new ArrayList<MaterialTransport>();
                    lists.add(mt);
                    maps.put(plantCode, lists);
                }
            }


            try {
                path = rejectionExcelExport(mts);
            } catch (Exception e) {
                e.printStackTrace();
            }

           try {
                EmailUtil.send(sender,re, subject, sdf.format(date) + content, path);
            } catch (MessagingException e) {
                saveEmailSendInfo(sender, re, "N");
            }
            saveEmailSendInfo(sender, re, "Y");
        }

        if(maps != null && maps.size() != 0){
            Set<String> sets = maps.keySet();
            if(sets != null && sets.size() != 0){
                for (String str : sets) {
                    List<MaterialTransport> materialTransports = maps.get(str);
                    if (materialTransports != null && materialTransports.size() != 0) {
                        try {
                            path = rejectionExcelExport(materialTransports);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            if(receiver.get(str) != null){
                                EmailUtil.send(sender, receiver.get(str), subject, sdf.format(date) + content, path);
                            }
                        } catch (MessagingException e) {
                            saveEmailSendInfo(sender, receiver.get(str), "N");
                        }
                        saveEmailSendInfo(sender, receiver.get(str), "Y");

                    }
                }

            }

        }

        return false;
    }

    @Override
    public void delEmailLog() {
        String str = "delete from t_emailLog";
        jdbcTemplate.update(str);
    }

    public String rejectionExcelExport(List<MaterialTransport> datas) throws Exception {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String formatdate = format.format(new Date());
        String title = "orderDetails  "+ formatdate;
        String creator = "";
        String path = System.getProperty("user.dir") + System.getProperty("file.separator") + title + "" + ".xls";

        creator = "";
        String[] hearders = null;
        String[] fields = null;

        hearders = new String[]{"发货仓库", "发货仓库名称", "delivery号", "物料号", "产品码", "物料描述", "发货数量", "已扫数量", "未扫数量", "状态"};// 表头数组

        fields = new String[]{"plantCode", "plantName", "delivery", "material", "productCode", "description", "deliveryQty", "sendDeliveryQty", "remainingQty", "flag"};// 对象属性数组


        TableData td = ExcelUtils.createTableData(datas, ExcelUtils.createTableHeader(hearders), fields);
        JsGridReportBase report = new JsGridReportBase();
        report.exportToExcelForEmail(title, creator, td, path);
        // retransports = null;
        return path;
    }


}
